import sys
from threading import Thread
import segyio
import numpy as np


def compare_segy_files(file1, file2, error_precise=0):
    print('在{}精度范围下：'.format(error_precise))
    with segyio.open(file1, "r", endian='little',ignore_geometry=True) as segy1:
        # 读取所有迹线数据并转换为 NumPy 数组
        traces1 = np.array([trace for trace in segy1.trace[:]])
    # 打开第二个文件
    with segyio.open(file2, "r", endian='little',ignore_geometry=True) as segy2:
        # 读取所有迹线数据并转换为 NumPy 数组
        traces2 = np.array([trace for trace in segy2.trace[:]])

    diff_mask = np.abs(np.abs(traces1) - np.abs(traces2)) > error_precise
    diff_hege=np.abs(np.abs(traces1) - np.abs(traces2)) <= error_precise

    # 使用 NumPy 的矢量化操作，得到一个True or False的numpy数组
    diff_count = np.count_nonzero(diff_mask)
    diff_hege_count=np.count_nonzero(diff_hege)
    # 统计 diff_mask 中 True 元素的数量，即差值小于等于 error_precise 的元素数量
    sample_num = len(traces1[0])
    total_trace = len(traces1)
    print('---------->>单轨迹取样点数目(sample_num)：{}'.format(sample_num))
    print('---------->>总轨迹数目(total_trace)：{}'.format(total_trace))
    print('---------->>不合格数为：{}'.format(diff_count))
    print('---------->>合格数为：{}'.format(diff_hege_count))
    print('---------->>不合格数/合格数：{:.2%}'.format(diff_count/diff_hege_count))
    #print('---------->>不合格数/合格数：{:.2%}'.format(diff_count / ((sample_num * total_trace)-diff_count)))
    print('---------->>不合格数/总数：{:.2%}'.format(diff_count / (sample_num * total_trace)))
    #return sample_num, total_trace, diff_count


if __name__ == '__main__':
    # 从命令行参数获取文件路径
    if len(sys.argv) not in (3, 4):
        print("请提供两个 SEG-Y 文件的路径作为参数，第一个参数为arm环境segy，第二个为x86环境，第三个为误差精度（如：0.001）")
        sys.exit(1)

    file1_path = sys.argv[1]
    file2_path = sys.argv[2]
    error_precise = float(sys.argv[3])
    t = Thread(target=compare_segy_files, args=(file1_path, file2_path, error_precise))
    #为多线程运行计算多个模块预留，暂未优化
    t.start()
